<template>
  <view class="container">
    <view class="header">
      <text class="title">发布评价</text>
    </view>
    
    <form class="review-form">
      <!-- 公司信息 -->
      <view class="form-group">
        <text class="label">公司名称</text>
        <view class="form-control">
          <text class="company-name">{{ companyName || '请选择公司' }}</text>
          <button class="select-btn" @click="toSelectCompany">选择</button>
        </view>
      </view>
      
      <!-- 职位信息 -->
      <view class="form-group">
        <text class="label">您的职位</text>
        <view class="form-control">
          <input type="text" v-model="position" placeholder="例如：研发部 · 前端工程师" />
        </view>
      </view>
      
      <!-- 多维度评分 -->
      <view class="form-group">
        <text class="label">维度评分</text>
        <view class="form-control">
          <view class="rating-item" v-for="(item, index) in ratingDimensions" :key="index">
            <text class="dimension-name">{{ item.description }}</text>
            <view class="stars">
              <div 
                class="star-item"
                :class="{ 'active': item.score >= i }"
                v-for="i in 5" 
                :key="i"
                @click="updateRating(index, i)">
                ★
              </div>
              <text class="score-text">{{ item.score }}分</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 优点 -->
      <view class="form-group">
        <text class="label">公司优点</text>
        <view class="form-control">
          <textarea 
            v-model="pros" 
            placeholder="请分享这家公司的优点..."
            :auto-height="true"
            maxlength="500"></textarea>
        </view>
      </view>
      
      <!-- 缺点 -->
      <view class="form-group">
        <text class="label">公司缺点</text>
        <view class="form-control">
          <textarea 
            v-model="cons" 
            placeholder="请分享这家公司的缺点..."
            :auto-height="true"
            maxlength="500"></textarea>
        </view>
      </view>
      
      <!-- 详细评价 -->
      <view class="form-group">
        <text class="label">详细评价</text>
        <view class="form-control">
          <textarea 
            v-model="content" 
            placeholder="请分享您在这家公司的工作体验，帮助更多人了解真实情况..."
            :auto-height="true"
            maxlength="1000"></textarea>
        </view>
      </view>
      
      <!-- 匿名选项 -->
      <view class="form-group">
        <view class="checkbox-group">
          <uni-checkbox v-model="anonymous" :checked="true">匿名发布</uni-checkbox>
          <text class="tip">匿名发布可以保护您的隐私</text>
        </view>
      </view>
      
      <!-- 提交按钮 -->
      <button class="submit-btn" @click="submitReview">发布评价</button>
    </form>
  </view>
</template>

<script>
import { getRatingDimensions, createUserReview, createReviewRating } from '@/api/company.js';

export default {
  data() {
    return {
      companyId: null,
      companyName: '',
      position: '',
      pros: '',
      cons: '',
      content: '',
      anonymous: true,
      // 多维度评分 - 将从API获取
      ratingDimensions: [],
      loading: false
    };
  },
  onLoad(options) {
    if (options.companyId) {
      this.companyId = options.companyId;
    }
    if (options.companyName) {
      this.companyName = options.companyName;
    }
    
    // 加载评价维度列表
    this.loadRatingDimensions();
  },
  methods: {
    // 加载评价维度列表
    async loadRatingDimensions() {
      try {
        const res = await getRatingDimensions({ status: 1,pageNum:1,pageSize:10 });
        if (res && res.rows && res.rows.length > 0) {
          // 为每个维度添加score属性
          this.ratingDimensions = res.rows.map(dimension => ({
            id: dimension.id,
            name: dimension.name,
            description: dimension.description,
            score: 0
          }));
        } else {
          // 如果没有获取到维度，使用默认维度作为降级方案
          this.ratingDimensions = [
            { id: 1, name: '薪资待遇', score: 0 },
            { id: 2, name: '工作环境', score: 0 },
            { id: 3, name: '企业文化', score: 0 },
            { id: 4, name: '发展前景', score: 0 },
            { id: 5, name: '工作生活平衡', score: 0 }
          ];
        }
      } catch (error) {
        console.error('获取评价维度失败:', error);
        // 使用默认维度作为降级方案
        this.ratingDimensions = [
          { id: 1, name: '薪资待遇', score: 0 },
          { id: 2, name: '工作环境', score: 0 },
          { id: 3, name: '企业文化', score: 0 },
          { id: 4, name: '发展前景', score: 0 },
          { id: 5, name: '工作生活平衡', score: 0 }
        ];
      }
    },
    toSelectCompany() {
      // 跳转到搜索页面并设置选择模式
      uni.switchTab({
        url: '/pages/search/search?selectMode=true'
      }).catch(err => {
        console.error('跳转到搜索页面失败:', err);
        uni.showToast({
          title: '页面跳转失败，请重试',
          icon: 'none'
        });
      });
    },
    // 更新评分
    updateRating(dimensionIndex, score) {
      this.$set(this.ratingDimensions, dimensionIndex, {
        ...this.ratingDimensions[dimensionIndex],
        score: score
      });
    },
    // 检查是否所有维度都已评分
    allDimensionsRated() {
      return this.ratingDimensions.every(dim => dim.score > 0);
    },
    async submitReview() {
      // 表单验证
      if (!this.companyId) {
        uni.showToast({
          title: '请选择公司',
          icon: 'none'
        });
        return;
      }
      
      if (!this.position.trim()) {
        uni.showToast({
          title: '请输入您的职位',
          icon: 'none'
        });
        return;
      }
      
      // 验证所有维度都已评分
      if (!this.allDimensionsRated()) {
        uni.showToast({
          title: '请完成所有维度的评分',
          icon: 'none'
        });
        return;
      }
      
      if (!this.pros.trim() && !this.cons.trim() && !this.content.trim()) {
        uni.showToast({
          title: '请至少填写一项评价内容',
          icon: 'none'
        });
        return;
      }
      
      // 构造评价内容（合并优点、缺点和详细评价）
      const fullContent = `职位：${this.position}\n\n优点：${this.pros}\n\n缺点：${this.cons}\n\n详细评价：${this.content}`;
      
	  // 获取userId
	    const cachedUserInfo = uni.getStorageSync('UserInfo');
      // 构造评价数据（根据数据库结构）
      const reviewData = {
        companyId: this.companyId,
        // 这里应该获取当前用户ID，暂时写死为1
        userId: cachedUserInfo.userId,
        // 昵称和头像URL应该从用户信息中获取
        nickName: this.anonymous ? '匿名用户' : cachedUserInfo.username,
        avatarUrl: '',
        content: fullContent,
        isAnonymous: this.anonymous ? 1 : 0,
        status: 1
      };
      
      // 提交评价
      uni.showLoading({
        title: '发布中...'
      });
      
      try {
        // 1. 首先提交评价主体信息
        const reviewRes = await createUserReview(reviewData);
        
        if (reviewRes.code === 200) {
          // 2. 评价提交成功后，提交维度评分数据
          const reviewId = reviewRes.data; // 假设接口返回评价ID
          
          // 批量提交维度评分
          const ratingPromises = this.ratingDimensions.map(dim => {
            return createReviewRating({
              reviewId: reviewId,
              dimensionId: dim.id,
              score: dim.score
            });
          });
          
          await Promise.all(ratingPromises);
          
          uni.hideLoading();
          uni.showToast({
            title: '评价发布成功',
            icon: 'success'
          });
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          throw new Error(reviewRes.msg || '发布失败');
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '发布失败: ' + (error.message || '请重试'),
          icon: 'none'
        });
        console.error('发布评价失败:', error);
      }
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #36D;
  color: #fff;
  position: relative;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.review-form {
  flex: 1;
  padding: 15px;
}

.form-group {
  margin-bottom: 15px;
  background-color: #fff;
  border-radius: 8px;
  padding: 12px 15px;
}

.label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  display: block;
}

.form-control {
  width: 100%;
}

.form-control input,
.form-control textarea {
  width: 100%;
  font-size: 14px;
  color: #333;
}

.form-control textarea {
  min-height: 80px;
  line-height: 1.6;
}

.company-name {
  font-size: 14px;
  color: #333;
  line-height: 36px;
}

.select-btn {
  width: 60px;
  height: 30px;
  line-height: 30px;
  background-color: #36D;
  color: #fff;
  border-radius: 4px;
  font-size: 14px;
  padding: 0;
}

.stars {
  display: flex;
  gap: 10px;
}

.star-item {
  display: inline-block;
  font-size: 24px;
  color: #ccc;
  cursor: pointer;
  transition: color 0.2s;
  margin-right: 8px;
}

.star-item.active {
  color: #FFCC00;
}

.star-item:active {
  transform: scale(0.95);
}

.checkbox-group {
  display: flex;
  align-items: center;
}

.tip {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
}

.submit-btn {
  width: 100%;
  height: 45px;
  line-height: 45px;
  background-color: #36D;
  color: #fff;
  border-radius: 8px;
  font-size: 16px;
  margin-top: 20px;
}
</style>
